using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Umi.Web.Metadatas.Exceptions;
using Umi.Web.Metadatas.StatusCodes;

namespace Umi.Web.Filters
{
    public class ExceptionFilter : IFilterMetadata, IExceptionFilter, IAsyncExceptionFilter
    {
        private readonly ILogger _logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            this._logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            _logger.LogError(context.Exception, "{0} throws an exception, not handled", context.HttpContext.Request.Path);
            if (context.ExceptionHandled)
                return;
            JsonResult jsonResult = new JsonResult(null);
            if (context.Exception is HttpStatusException webException)
            {
                jsonResult.Value = new
                {
                    webException.StatusCode.Code,
                    webException.StatusCode.Message
                };
                jsonResult.StatusCode = webException.StatusCode.Code;
            }
            else
            {
                jsonResult.Value = new
                {
                    HttpStatusCodes.INTERNAL_SERVER_ERROR.Code,
                    context.Exception.Message
                };
                jsonResult.StatusCode = HttpStatusCodes.INTERNAL_SERVER_ERROR.Code;
            }
            context.Result = jsonResult;
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            this.OnException(context);
            return Task.CompletedTask;
        }
    }
}
